package com.slwish.xty.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.slwish.common.base.PresenterToolbarActivity;
import com.slwish.common.config.Contants;
import com.slwish.common.dialog.PictureDialog;
import com.slwish.common.utils.IntentUtils;
import com.slwish.common.utils.TimeUtils;
import com.slwish.xty.R;
import com.slwish.xty.base.BaseApplication;
import com.slwish.xty.event.SubscribeEvent;
import com.slwish.xty.mvp.contract.SignContract;
import com.slwish.xty.mvp.presenter.SignPresenter;
import com.slwish.xty.utils.LocaServiceUtils;
import com.slwish.xty.utils.MapUtils;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 签到
 */
public class SignActivity extends PresenterToolbarActivity<SignContract.Presenter> implements SignContract.View {

    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_location)
    TextView tv_location;
    @BindView(R.id.mapview)
    MapView mMapView;
    private BaiduMap mBaiduMap;
    private LocationClient mLocClient;
    private int mCurrentDirection = 0;
    private double mCurrentLat = 0.0;//纬度
    private double mCurrentLon = 0.0;//经度
    //    private static final int accuracyCircleFillColor = 0xAAFFFF88;
//    private static final int accuracyCircleStrokeColor = 0xAA00FF00;
    boolean isFirstLoc = true; // 是否首次定位
    private MyLocationData locData;
    private float mCurrentAccracy;
    //    public MyLocationListenner myListener = new MyLocationListenner();
    private BitmapDescriptor mCurrentMarker;
    private String city;
    private String street;
    private int orderId;//订单号
    private int position;
    private PictureDialog dialog;

    @Override
    protected int getLayoutId() {
        return R.layout.act_sign;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        setTitle(R.string.sign_text);
        orderId = getIntent().getIntExtra(Contants.ID, 0);
        position = getIntent().getIntExtra("POSITION", 0);
//        LogUtils.i("xx","orderId:"+orderId);
        tvTime.setText(String.format(getString(R.string.sign_time_text), TimeUtils.getCurTimeString()));
        dialog = new PictureDialog(mContext);
        dialog.show();
        initBaiduMap();
    }

    private void initBaiduMap() {
        mBaiduMap = mMapView.getMap();
        // 开启定位图层
//        mBaiduMap.setMyLocationEnabled(true);
        // 定位初始化
        LocaServiceUtils locaServiceUtils = BaseApplication.getLocaService();
        locaServiceUtils.registerListener(new BDAbstractLocationListener() {
            @Override
            public void onReceiveLocation(final BDLocation location) {
                // map view 销毁后不在处理新接收的位置
                if (location == null || mMapView == null) {
                    return;
                }
                dialog.dismiss();
                SignActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (location.getCity() != null && location.getDistrict() != null
                                && location.getStreet() != null && location.getStreetNumber() != null)
                            tv_location.setText(location.getCity() + location.getDistrict() + location.getStreet() + location.getStreetNumber());
                    }
                });
//                location.getProvince();//省
                //市
                city = location.getCity();
//                location.getDistrict();//区
                //街道
                street = location.getStreet();
//                List<Poi> poiList = location.getPoiList();
                mCurrentLat = location.getLatitude();
                mCurrentLon = location.getLongitude();
                mCurrentAccracy = location.getRadius();
                locData = new MyLocationData.Builder()
                        .accuracy(location.getRadius())
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(mCurrentDirection).latitude(location.getLatitude())
                        .longitude(location.getLongitude()).build();
                mBaiduMap.setMyLocationData(locData);
                if (isFirstLoc) {
                    isFirstLoc = false;
                    LatLng latLng = new LatLng(location.getLatitude(),
                            location.getLongitude());
//                    MapStatus.Builder builder = new MapStatus.Builder();
//                    builder.target(latLng).zoom(19.0f);
//                    mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                    MapUtils.getMarkerAndMove(mBaiduMap, latLng, R.mipmap.dtdw);
                }

            }
        });
        locaServiceUtils.start();
        mLocClient = locaServiceUtils.getLocationClient();
        // 修改为自定义marker
//        mCurrentMarker = BitmapDescriptorFactory
//                .fromResource(R.mipmap.dtdwss);
//        mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
//                MyLocationConfiguration.LocationMode.NORMAL, true, mCurrentMarker));

    }

    @Override
    protected SignContract.Presenter initPresenter() {
        return new SignPresenter(this);
    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onStop() {
        //取消注册传感器监听
//        mSensorManager.unregisterListener(this);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        if (mLocClient != null)
            mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        super.onDestroy();
    }

    @OnClick({R.id.tv_addr_wt, R.id.btn_see})
    public void setOnClick(View view) {
        switch (view.getId()) {
            case R.id.btn_see://提交
                mPresenter.signInSubscribe(mContext, orderId, mCurrentLon, mCurrentLat);
                break;
            case R.id.tv_addr_wt://地点微调
                Bundle bundle = new Bundle();
                bundle.putString("CITY", city);
                bundle.putString("ADDRESS", street);
                IntentUtils.startActivityForResult(mContext, SignAdjustActivity.class, bundle, 1000);
                break;
        }

    }

    /**
     * 签到成功
     */
    @Override
    public void signInSubscribeSuccess() {
        EventBus.getDefault().post(new SubscribeEvent("刷新", position));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1000 && resultCode == 100) {
            try {
                if (data != null) {
                    PoiInfo model = data.getParcelableExtra("MODEL");
                    tv_location.setText(model.name);
                    mCurrentLat = model.location.latitude;
                    mCurrentLon = model.location.longitude;
//                LogUtils.i("xx","mCurrentLat:"+mCurrentLat);
//                LogUtils.i("xx","mCurrentLon:"+mCurrentLon);
                    MapUtils.getMarkerAndMove(mBaiduMap, model.location, R.mipmap.dtdw);
                }
            } catch (Exception e) {
            }
        }

    }
}
